package org.example;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/S")
public class SessionSecurity extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Object user = null;
        session.setAttribute("user", user);
        Cookie cookie = new Cookie("XXX", session.getId());
        cookie.setMaxAge(3600); // 设置有效期为1小时
        cookie.setDomain("example.com");
        cookie.setPath("/");
        cookie.setHttpOnly(true); //设置Cookie为HttpOnly，防止JavaScript访问，增强安全性。
        cookie.setSecure(true); //表示仅通过HTTPS传输此Cookie，增加安全性。
        resp.addCookie(cookie);
    }

//跨站脚本攻击（XSS）和防御
    public String escapeXSS(String userInput) {
        if (userInput == null) {
            return null;
        }
        return userInput.replace("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace("\"", "&quot;")
                .replace("'", "&#39;");
    }

//跨站请求伪造（CSRF）和防御
    public String generateCsrfToken(HttpSession session) {
        String csrfToken = java.util.UUID.randomUUID().toString();
        session.setAttribute("csrfToken", csrfToken);
        return csrfToken;
    }
}

